#!/usr/bin/env bash
set -euo pipefail

# Optional: pass proxy via env PROXY or --proxy arg. Default probes 127.0.0.1:7890
PROXY=${PROXY:-}
if [[ ${1:-} == "--proxy" && -n ${2:-} ]]; then
  PROXY="$2"; shift 2
fi

probe_proxy() {
  local url="$1"
  echo "[proxy] Probing $url ..." >&2
  # Use a short HEAD request to PyPI (less likely blocked than google)
  if curl -sS --proxy "$url" --max-time 5 -I https://pypi.org/simple/ >/dev/null; then
    echo OK
  else
    echo FAIL
  fi
}

if [[ -z "$PROXY" ]]; then
  # Try typical mixed-port of Clash at 7890
  PROXY_CANDIDATE="http://127.0.0.1:7890"
  if [[ $(probe_proxy "$PROXY_CANDIDATE") == OK ]]; then
    PROXY="$PROXY_CANDIDATE"
  fi
fi

if [[ -n "$PROXY" ]]; then
  echo "[proxy] Using proxy: $PROXY"
  export HTTP_PROXY="$PROXY" HTTPS_PROXY="$PROXY" ALL_PROXY="$PROXY"
  export http_proxy="$PROXY" https_proxy="$PROXY" all_proxy="$PROXY"
else
  echo "[proxy] No proxy configured. Proceeding direct."
fi

echo "[1/6] Checking Homebrew..."
if ! command -v brew >/dev/null 2>&1; then
  echo "Error: Homebrew not found. Install via https://brew.sh and rerun." >&2
  exit 1
else
  brew -v | head -n1
fi

echo "[2/6] Ensuring Miniforge (conda) is installed..."
if ! command -v conda >/dev/null 2>&1; then
  echo "Installing Miniforge via Homebrew cask (requires network & password if prompted)..."
  brew install --cask miniforge
fi

# Locate conda binary robustly
find_conda() {
  if command -v conda >/dev/null 2>&1; then command -v conda; return; fi
  for p in \
    "/opt/homebrew/Caskroom/miniforge/base/bin/conda" \
    "/opt/miniforge3/bin/conda" \
    "/usr/local/miniforge3/bin/conda" \
    "$HOME/miniforge3/bin/conda" \
    ; do
    [[ -x "$p" ]] && { echo "$p"; return; }
  done
  return 1
}

CONDA_BIN="$(find_conda)" || { echo "Error: conda not found after installation." >&2; exit 1; }
echo "conda bin: $CONDA_BIN"

ENV_NAME="zny311"
PYVER="3.11"

echo "[3/6] Creating conda env $ENV_NAME (python=$PYVER)..."
"$CONDA_BIN" create -n "$ENV_NAME" python="$PYVER" -y

# Helper to run commands inside env without shell init side effects
CRUN() { "$CONDA_BIN" run -n "$ENV_NAME" "$@"; }

echo "[4/6] Installing Python packages (project + PyTorch/MPS)..."
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$ROOT_DIR"

CRUN python -m pip install --upgrade pip setuptools wheel
CRUN pip install -r requirements.txt
# macOS MPS wheels are distributed on the cpu index URL
CRUN pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu

echo "[5/6] Verifying environment (torch+MPS, ultralytics, opencv)..."
CRUN python - <<'PY'
import sys
print('python:', sys.version)
try:
  import torch
  print('torch:', torch.__version__)
  print('mps_available:', getattr(torch.backends,'mps',None) and torch.backends.mps.is_available())
  try:
    _ = torch.ones(1, device='mps')
    print('mps_tensor_ok:', True)
  except Exception as e:
    print('mps_tensor_ok:', False, '|', e)
except Exception as e:
  print('torch_error:', e)
try:
  import ultralytics; print('ultralytics:', ultralytics.__version__)
except Exception as e:
  print('ultralytics_error:', e)
try:
  import cv2; print('opencv:', cv2.__version__)
except Exception as e:
  print('opencv_error:', e)
PY

echo "[6/6] Done. Usage:"
cat <<USAGE

Activate env for current shell:
  source "$(dirname "$CONDA_BIN")/../etc/profile.d/conda.sh" && conda activate $ENV_NAME

Or run without activation (example):
  "$CONDA_BIN" run -n $ENV_NAME python src/app.py --cfg configs/config.yaml

USAGE
